package com.crm.api.controller;

import com.crm.api.common.Result;
import com.crm.api.entity.Business;
import com.crm.api.service.BusinessService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.Map;

/**
 * 业务控制器
 */
@Slf4j
@RestController
@RequestMapping("/businesses")
public class BusinessController {

    @Autowired
    private BusinessService businessService;

    /**
     * 获取业务列表
     */
    @GetMapping
    public Result<Map<String, Object>> getBusinesses(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String businessName,
            @RequestParam(required = false) String businessStatus,
            @RequestParam(required = false) Integer customerId,
            @RequestParam(required = false) Integer businessTypeId,
            @RequestParam(required = false) Integer responsibleEmployeeId) {
        
        log.info("获取业务列表: page={}, size={}, businessName={}, businessStatus={}", 
                page, size, businessName, businessStatus);
        
        Map<String, Object> result = businessService.getBusinesses(
                page, size, businessName, businessStatus, customerId, businessTypeId, responsibleEmployeeId);
        
        return Result.success(result);
    }

    /**
     * 获取业务详情
     */
    @GetMapping("/{id}")
    public Result<Map<String, Object>> getBusiness(@PathVariable Integer id) {
        log.info("获取业务详情: id={}", id);
        
        Map<String, Object> businessDetail = businessService.getBusinessDetailById(id);
        if (businessDetail == null) {
            return Result.error(404, "业务不存在");
        }
        
        return Result.success(businessDetail);
    }

    /**
     * 创建业务
     */
    @PostMapping
    public Result<Business> createBusiness(@Valid @RequestBody Business business) {
        // 获取当前用户信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        
        log.info("创建业务: businessName={}, creator={}", business.getBusinessName(), username);
        
        Business createdBusiness = businessService.createBusiness(business, username);
        return Result.success(createdBusiness);
    }

    /**
     * 更新业务
     */
    @PutMapping("/{id}")
    public Result<Business> updateBusiness(@PathVariable Integer id, @Valid @RequestBody Business business) {
        log.info("更新业务: id={}, businessName={}", id, business.getBusinessName());
        
        business.setId(id);
        Business updatedBusiness = businessService.updateBusiness(business);
        
        if (updatedBusiness == null) {
            return Result.error(404, "业务不存在");
        }
        
        return Result.success(updatedBusiness);
    }

    /**
     * 删除业务
     */
    @DeleteMapping("/{id}")
    public Result<Void> deleteBusiness(@PathVariable Integer id) {
        log.info("删除业务: id={}", id);
        
        boolean deleted = businessService.deleteBusiness(id);
        if (!deleted) {
            return Result.error(404, "业务不存在");
        }
        
        return Result.success();
    }

    /**
     * 更新业务状态
     */
    @PatchMapping("/{id}/status")
    public Result<Void> updateBusinessStatus(@PathVariable Integer id, @RequestBody Map<String, String> request) {
        String businessStatus = request.get("businessStatus");
        log.info("更新业务状态: id={}, status={}", id, businessStatus);
        
        boolean updated = businessService.updateBusinessStatus(id, businessStatus);
        if (!updated) {
            return Result.error(404, "业务不存在");
        }
        
        return Result.success();
    }

    /**
     * 更新业务进度备注
     */
    @PatchMapping("/{id}/progress")
    public Result<Void> updateBusinessProgress(@PathVariable Integer id, @RequestBody Map<String, String> request) {
        String progressNotes = request.get("progressNotes");
        log.info("更新业务进度备注: id={}", id);
        
        boolean updated = businessService.updateBusinessProgress(id, progressNotes);
        if (!updated) {
            return Result.error(404, "业务不存在");
        }
        
        return Result.success();
    }

    /**
     * 获取业务统计信息
     */
    @GetMapping("/stats")
    public Result<Map<String, Object>> getBusinessStats(
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate,
            @RequestParam(required = false) Integer businessTypeId) {
        
        log.info("获取业务统计信息: startDate={}, endDate={}, businessTypeId={}", 
                startDate, endDate, businessTypeId);
        
        Map<String, Object> stats = businessService.getBusinessStats(startDate, endDate, businessTypeId);
        return Result.success(stats);
    }

    /**
     * 获取客户业务统计
     */
    @GetMapping("/customer-stats")
    public Result<List<Map<String, Object>>> getCustomerBusinessStats() {
        log.info("获取客户业务统计");
        
        List<Map<String, Object>> stats = businessService.getCustomerBusinessStats();
        return Result.success(stats);
    }
}